﻿using UnityEngine;
using System.Collections;

public class NewSpawn :MonoBehaviour {

	// Use this for initialization

	public Transform playerPrefab ;
	public ArrayList playerScripts  = new ArrayList();

	void OnServerInitialized(){
		//Spawn a player for the server itself
		Spawnplayer(Network.player);
	}

	void OnPlayerConnected(NetworkPlayer newPlayer) {
		//A player connected to me(the server)!
		Spawnplayer(newPlayer);
	}

	void Spawnplayer(NetworkPlayer newPlayer ){
		//Called on the server only

		int playerNumber  = int.Parse(newPlayer+"");
		//Instantiate a new object for this player, remember;
		//the server is therefore the owner.
		Transform myNewTrans  = (Transform)Network.Instantiate(playerPrefab,transform.position, transform.rotation, playerNumber);

		//Get the networkview of this new transform


		NetworkView newObjectsNetworkview  = myNewTrans.networkView;

		//Keep track of this new player so we can properly destroy it
		//when required.
		playerScripts.Add(myNewTrans.GetComponent("Basics6"));

		//Call an RPC on this new networkview, set the player
		//who controls this player
		newObjectsNetworkview.RPC("SetPlayer", RPCMode.AllBuffered, newPlayer);
	}

	void OnPlayerDisconnected(NetworkPlayer player) {
		Debug.Log("Clean up after player " + player);

		foreach(Basics6 script in playerScripts){
			if(player==script.owner){
				//remove the bufferd SetPlayer call
				Network.RemoveRPCs(script.gameObject.networkView.viewID);
				//Destroying the GO will destroy everything
				Network.Destroy(script.gameObject);
				playerScripts.Remove(script);
				break;
			}
		}

		//Remove the buffered RPC call for instantiate for this player.
		int playerNumber  = int.Parse(player+"");
		Network.RemoveRPCs(Network.player, playerNumber);

		// The next destroys will not destroy anything since the players never
		// instantiated anything nor buffered RPCs


		Network.RemoveRPCs(player);
		Network.DestroyPlayerObjects(player);
	}

	void OnDisconnectedFromServer(NetworkDisconnection info ) {
		Debug.Log("Resetting the scene the easy way.");
		Application.LoadLevel(Application.loadedLevel);
	}
}
